//
//  HSongItem.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/18.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HSongItem.h"
#import "HCoreConfig.h"
#import "FMDB.h"
#import "HPlaylistItem.h"
#import "iTunes.h"
#import "TagReader.h"

@implementation HSongItem


#pragma mark ------------初始化----------
-(id)init {
    self=[super init];
    if (self) {
        self.islike=NO;
    }

    return self;
}


//-(void)assignWithItem:(HSongItem*)songitem{
//
//    self.songType = (songitem==nil ?@"": songitem.songType);
//    self.localPath =(songitem==nil ?@"": songitem.localPath);;
//    self.urlPath =(songitem==nil ?@"": songitem.urlPath);;
//    self.songName =(songitem==nil ?@"": songitem.songName);
//    self.songDuration =(songitem==nil ?0: songitem.songDuration);
//    self.lyricsLocalPath =(songitem==nil ?@"": songitem.lyricsLocalPath);
//    self.albumLocalPath =(songitem==nil ?@"": songitem.albumLocalPath);
//    self.islike = (songitem==nil ?NO: songitem.islike);
//    self.playListSyncID =(songitem==nil ?@"": songitem.playListSyncID);
//    self.syncid =(songitem==nil ?@"": songitem.syncid);
//    self.trackInfo =(songitem==nil ?@"": songitem.trackInfo);;
//    self.generateByItunesLibrary=(songitem==nil ?NO: songitem.generateByItunesLibrary);;//mark is from itunes
//
//    self.album =(songitem==nil ?@"": songitem.album);;
//    self.artist =(songitem==nil ?@"": songitem.artist);;
//    self.bookmark = songitem.bookmark;
//}


#pragma mark DB------
-(id)initWithResultset:(FMResultSet *)rs{
    self=[super init];
    if (self) {
     
        self.songType =CHECKSTR([rs stringForColumn:@"songType"]);
        self.localPath =CHECKSTR([rs stringForColumn:@"localPath"]);
        self.urlPath =CHECKSTR([rs stringForColumn:@"urlPath"]);
        self.songName =CHECKSTR([rs stringForColumn:@"songName"]);
        self.songDuration =[[rs stringForColumn:@"songDuration"] integerValue];
        self.lyricsLocalPath =CHECKSTR([rs stringForColumn:@"lyricsLocalPath"]);
        self.albumLocalPath =CHECKSTR([rs stringForColumn:@"albumLocalPath"]);
        self.islike =[[rs stringForColumn:@"islike"] boolValue];
        self.playListSyncID =CHECKSTR([rs stringForColumn:@"playListSyncID"]);
        self.syncid =CHECKSTR([rs stringForColumn:@"syncID"]);
        self.trackInfo =CHECKSTR([rs stringForColumn:@"trackInfo"]);
        self.album =CHECKSTR([rs stringForColumn:@"album"]);
        self.artist =CHECKSTR([rs stringForColumn:@"artist"]);
        self.bookmark = [rs dataForColumn:@"bookmark"];
        
        
    }
    
    return self;
}


-(id)initWithResultset:(FMResultSet *)rs andPlaylistItem:(HPlaylistItem*)pitem{


    self=[super init];
    if (self) {
        
        self.songType =CHECKSTR([rs stringForColumn:@"songType"]);
        self.localPath =CHECKSTR([rs stringForColumn:@"localPath"]);
        self.urlPath =CHECKSTR([rs stringForColumn:@"urlPath"]);
        self.songName =CHECKSTR([rs stringForColumn:@"songName"]);
        self.songDuration =[[rs stringForColumn:@"songDuration"] integerValue];
        self.lyricsLocalPath =CHECKSTR([rs stringForColumn:@"lyricsLocalPath"]);
        self.albumLocalPath =CHECKSTR([rs stringForColumn:@"albumLocalPath"]);
        self.islike =[[rs stringForColumn:@"islike"] boolValue];
        self.playListSyncID =pitem.syncid;
        self.syncid =CHECKSTR([rs stringForColumn:@"syncID"]);
        self.trackInfo =CHECKSTR([rs stringForColumn:@"trackInfo"]);
        
        self.album =CHECKSTR([rs stringForColumn:@"album"]);
        self.artist =CHECKSTR([rs stringForColumn:@"artist"]);
        self.bookmark = [rs dataForColumn:@"bookmark"];
        
        
    }
    return self;




}



#pragma mark itunes track dic------
//file:///Users/hament/Music/iTunes/iTunes%20Music%20Library.xml
//isfavourite: 是否来自itunes favourite
-(id)initWithItuneTrackDic:(NSDictionary *)songitem isfavourite:(BOOL)flag{
    
    
    self=[super init];
    if (self) {
        
        NSString * songDuration=songitem[@"Total Time"];
        NSString * localPath=songitem[@"Location"];
        NSString * artist=songitem[@"Artist"];
        NSString * album=songitem[@"Album"];
        localPath=[localPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //debugLog(@"localPath:%@",localPath);
         NSMutableString * handleLocation=[NSMutableString stringWithString:localPath];
        
        if ([localPath hasPrefix:@"file://localhost"]) {
            
            NSRange wholeShebang = NSMakeRange(0, 16);
            
            [handleLocation replaceOccurrencesOfString: @"file://localhost"
                                            withString: @""
                                               options: 0
                                                 range: wholeShebang];
        } else if ([localPath hasPrefix:@"file://"]) {
     
        NSRange wholeShebang = NSMakeRange(0, 7);
     
        [handleLocation replaceOccurrencesOfString: @"file://"
                                     withString: @""
                                        options: 0
                                          range: wholeShebang];
 } 
     
     
     
     
        NSString * Rating =CHECKSTR(songitem[@"Rating"]);
        int  ratingValue=[Rating intValue];
        
        self.songType =CHECKSTR(localPath.pathExtension);
        self.localPath =handleLocation;
        self.urlPath =@"";
        self.songName =songitem[@"Name"];
        self.songDuration =[songDuration integerValue];
        self.lyricsLocalPath =@"";
        self.albumLocalPath =@"";
        self.islike = (ratingValue>70 ? YES : NO);//80~100代表like
        self.playListSyncID =(flag ? likeSyncid : itunesSyncid);//分类 syncid
        self.syncid =((NSNumber*)songitem[@"Track ID"]).stringValue; //用 itunes 的trackid
        self.trackInfo =@"";
        self.generateByItunesLibrary=YES;//mark is from itunes
        self.album =CHECKSTR(album);
        self.artist =CHECKSTR(artist);
        self.bookmark = nil;//itunes音乐不需要bookmark
        
        
    }
    
    return self;
    
    
    
    
}



#pragma mark  init itunesTrack
-(id)initWithItuneTrackEntity:(iTunesFileTrack *)ituneTrack isfavourite:(BOOL)flag{


    self=[super init];
    if (self) {
        
        //ituneTrack.databaseID,ituneTrack.persistentID(十进制) 这两个会发生变化,值不唯一,但 xml里面每首歌的persistent ID是唯一的(十六进制)
        
//        debugLog(@"track:%d,persistentID:%d,name:%@",ituneTrack.databaseID,ituneTrack.persistentID,ituneTrack.name);
//        debugLog(@"location:%@",ituneTrack.location);
//        debugLog(@"duration:%f",ituneTrack.duration);
//        debugLog(@"rating:%d",ituneTrack.rating);
//        debugLog(@"track id:%d",ituneTrack.databaseID);
//        debugLog(@"persistentID:%d",ituneTrack.persistentID);
        
        
        
        ///*

        NSURL * urlpath=ituneTrack.location;
        NSString * localPath=urlpath.path;
        NSString * artist=ituneTrack.artist;
        NSString * album=ituneTrack.album;
        NSMutableString * handleLocation=[NSMutableString stringWithString:localPath];
        
        if ([localPath hasPrefix:@"file://localhost"]) {
            
            NSRange wholeShebang = NSMakeRange(0, 16);
            
            [handleLocation replaceOccurrencesOfString: @"file://localhost"
                                            withString: @""
                                               options: 0
                                                 range: wholeShebang];
        } else if ([localPath hasPrefix:@"file://"]) {
            
            NSRange wholeShebang = NSMakeRange(0, 7);
            
            [handleLocation replaceOccurrencesOfString: @"file://"
                                            withString: @""
                                               options: 0
                                                 range: wholeShebang];
        }
        
        
        
        

        
        self.songType =CHECKSTR(localPath.pathExtension);
        self.localPath =handleLocation;
        self.urlPath =@"";
        self.songName =ituneTrack.name;
        self.songDuration =(NSUInteger)(ituneTrack.duration*1000);
        self.lyricsLocalPath =@"";
        self.albumLocalPath =@"";
        self.islike = (ituneTrack.rating>75 ? YES : NO);//80~100代表like
        self.playListSyncID =(flag ? likeSyncid : itunesSyncid);//分类 syncid
        self.syncid = [NSString stringWithFormat:@"%d",ituneTrack.databaseID] ; //用 itunes app的trackid,这是会发生变化的
        self.trackInfo =@"";
        self.generateByItunesLibrary=YES;//mark is from itunes
        
        self.album =CHECKSTR(album);
        self.artist =CHECKSTR(artist);
        self.bookmark = nil;//itunes音乐不需要bookmark
        
      //*/
    }
    
    return self;
    

}

+(id)tempSongItemWithPath:(NSString*)path{

    NSFileManager * fm=[NSFileManager defaultManager];
    
    if([fm fileExistsAtPath:path] && [fm isReadableFileAtPath:path]) {
    
    
        NSURL * fileurl=[[NSURL alloc] initFileURLWithPath:path];
        //如果能获取到duration,视为合法音乐格式
        NSUInteger duration=[[HCoreConfig shareConfig] getSoundDuration:fileurl];
        if (duration!=InvalidSoundDuration) {
            
            
            TagReader *t = [[TagReader alloc] initWithFileAtPath:path];
            
            HSongItem * songItem=[[HSongItem alloc] init];
            
            //song localpath
            songItem.localPath=path;
            
            //song name
            if (t.title==nil) {
                NSString * filename=[path lastPathComponent];
                songItem.songName=filename;
                //debugLog(@"name:%@",songItem.songName);
            } else {
                songItem.songName=t.title;
            }
            
            //duration
            songItem.songDuration=duration;
            
            //song type
            songItem.songType=CHECKSTR(path.pathExtension);
            
            songItem.islike=NO;
            songItem.trackInfo =@"";
            songItem.lyricsLocalPath =@"";
            songItem.albumLocalPath =@"";
            songItem.urlPath =@"";
            
            //artist
            songItem.artist=CHECKSTR(t.artist);
            
            //album
            songItem.album=CHECKSTR(t.album);
            
            songItem.syncid=[HCoreConfig generateSyncID];
            songItem.playListSyncID=tempSyncid;
            
            //bookmark
            //创建score bookmark
            NSError * bookmarkerror=nil;
            NSData * data =[fileurl bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
                             includingResourceValuesForKeys:nil
                                              relativeToURL:nil
                                                      error:&bookmarkerror];
            
            
            if (bookmarkerror) {
                debugLog(@"insert song bookmarkerror:%@",bookmarkerror.description);
            } else {
                songItem.bookmark=data;
                
            }
            
            
            return songItem;

        }
        
    }
    
    
    return nil;
    
    





}



-(NSURL*)audioFileURL{


    NSURL * url=nil;
    
    NSString  * locpath=CHECKSTR(self.localPath);
    NSString  * onlinepath=CHECKSTR(self.urlPath);
    
    //先播放本地
    if (![locpath isEqualToString:@""]) {
        url=[NSURL fileURLWithPath:locpath];
    }
    //再检测网络
    else if(![onlinepath isEqualToString:@""]) {
        url=[NSURL URLWithString:locpath];
    }

    return url;
}


#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {

    [aCoder encodeObject:self.songType forKey:@"songType"];
    [aCoder encodeObject:self.localPath forKey:@"localPath"];
    [aCoder encodeObject:self.urlPath forKey:@"urlPath"];
    [aCoder encodeObject:self.songName forKey:@"songName"];
    [aCoder encodeInteger:self.songDuration forKey:@"songDuration"];
    [aCoder encodeObject:self.lyricsLocalPath forKey:@"lyricsLocalPath"];
    [aCoder encodeObject:self.albumLocalPath forKey:@"albumLocalPath"];
    [aCoder encodeObject:self.trackInfo forKey:@"trackInfo"];
    [aCoder encodeObject:self.syncid forKey:@"syncid"];
    [aCoder encodeBool:self.islike forKey:@"islike"];
    [aCoder encodeBool:self.generateByItunesLibrary forKey:@"generateByItunesLibrary"];
    [aCoder encodeObject:self.playListSyncID forKey:@"playListSyncID"];
    
    [aCoder encodeObject:self.album forKey:@"album"];
    [aCoder encodeObject:self.artist forKey:@"artist"];
    [aCoder encodeObject:self.bookmark forKey:@"bookmark"];

}

- (id)initWithCoder:(NSCoder *)aDecoder {
    
    self = [super init];
    
    if (self ) {
        self.songType = [aDecoder decodeObjectForKey:@"songType"];
        self.localPath = [aDecoder decodeObjectForKey:@"localPath"];
        self.urlPath = [aDecoder decodeObjectForKey:@"urlPath"];
        self.songName = [aDecoder decodeObjectForKey:@"songName"];
        self.songDuration = [aDecoder decodeIntegerForKey:@"songDuration"];
        self.lyricsLocalPath = [aDecoder decodeObjectForKey:@"lyricsLocalPath"];
        self.albumLocalPath = [aDecoder decodeObjectForKey:@"albumLocalPath"];
        self.trackInfo = [aDecoder decodeObjectForKey:@"trackInfo"];
        self.syncid = [aDecoder decodeObjectForKey:@"syncid"];
        self.islike =[aDecoder decodeBoolForKey:@"islike"];
        self.generateByItunesLibrary =[aDecoder decodeBoolForKey:@"generateByItunesLibrary"];
        self.playListSyncID= [aDecoder decodeObjectForKey:@"playListSyncID"];

        self.artist= [aDecoder decodeObjectForKey:@"artist"];
        self.album= [aDecoder decodeObjectForKey:@"album"];
        self.bookmark= [aDecoder decodeObjectForKey:@"bookmark"];

    }
    return self;
}











#pragma mark NSPasteboardWriting

//告诉粘贴板 可以 写入何种data type的数据, type的格式遵循 苹果UTI的命名方式,
//如: com.apple.cocoa.pasteboard.color 指 nscolor类
//如果想知道某个东西是属于何种uti, 可以用实现了NSPasteboarddelegate的类执行writableTypesForPasteboard,如NSString, NSAttributedString, NSURL, NSColor, NSSound, NSImage, and NSPasteboardItem 等等

- (NSArray *)writableTypesForPasteboard:(NSPasteboard *)pasteboard {
    
    NSArray *typeArr =@[HSONGITEMTYPE,(id)kUTTypeURL,NSPasteboardTypeString];
    
    //NSLog(@"NSPasteboardTypeString:%@",NSPasteboardTypeString);//public.utf8-plain-text
    return typeArr;
}



//如果返回0 ,数据会立即写入到粘贴板,如果返回其他,数据会被接受,但不会立即写入粘贴板
- (NSPasteboardWritingOptions)writingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard {
    // debugLog(@"11111writeoption type:%@",type);
    //这里 直接 return 0就行;
    return 0;
}


//可以自定义根据不同的类型返回的数据是什么,如果是plist兼容格式的数据会返回对应的格式,如字符串, 其他都会被转换为nsdata
//可以使用 pasteboardPropertyListForType: 来确定某种类型写入何种内容到粘贴板
- (id)pasteboardPropertyListForType:(NSString *)type {
   
     //debugLog(@"write type:%@",type);
    id obj =nil;
    if ([type isEqualToString:NSPasteboardTypeString] ) {
        obj=CHECKSTR(self.songName);
        
    } else if ( UTTypeConformsTo((__bridge CFStringRef)type, kUTTypeURL)){
    
        
        NSURL * url=[NSURL fileURLWithPath:CHECKSTR(self.localPath)];
        obj= [url pasteboardPropertyListForType:type]; //需要返回cfstring

        
    } else if ([type isEqualToString:HSONGITEMTYPE]){
    
         obj = [NSKeyedArchiver archivedDataWithRootObject:self];


    } else if ([type isEqualToString:HSONGIDATATYPE]) {
    
        obj=[NSData dataWithContentsOfFile:CHECKSTR(self.localPath)];
    
    }

    
    return obj;
}

#pragma mark NSPasteboardReading

+ (NSArray *)readableTypesForPasteboard:(NSPasteboard *)pasteboard {
    return @[(id)kUTTypeFileURL,HSONGITEMTYPE,NSPasteboardTypeString];//顺序很重要,会依次按照循序解析pasteboard内容
}

+ (NSPasteboardReadingOptions)readingOptionsForType:(NSString *)type pasteboard:(NSPasteboard *)pasteboard {
    
    //debugLog(@"readoption type:%@",type);
    if ([type isEqualToString:NSPasteboardTypeString] || UTTypeConformsTo((__bridge CFStringRef)type, kUTTypeURL) ) {
        return NSPasteboardReadingAsString;
        
    } else if ([type isEqualToString:HSONGIDATATYPE]) {
    
        return NSPasteboardReadingAsData;
    }
    
    return NSPasteboardReadingAsKeyedArchive;//会自动调用 initwithcoder:
}


- (id)initWithPasteboardPropertyList:(id)propertyList ofType:(NSString *)type {
    
 
    //debugLog(@"read type:%@",type);
    
    if ( UTTypeConformsTo((__bridge CFStringRef)type, kUTTypeURL)) {
        NSURL *url = [[NSURL alloc] initWithPasteboardPropertyList:propertyList ofType:type];
        self=[super init];
        self.localPath=url.path;
        self.songType=url.pathExtension;
        
        
        
    } else if ([type isEqualToString:NSPasteboardTypeString]) {
         self=[super init];
        self.songName=propertyList;
        
    } else
        return nil;
    
//    else if ([type isEqualToString:HSONGITEMTYPE]) {
//    
//        self= (HSongItem*)[NSKeyedUnarchiver unarchiveObjectWithData:propertyList];
//        
//
//    
//    }
    
    return self;
}

@end
